package com.hkbigdata.mall.miaosha.webscoket;

/**
 * ClassName: Aw
 * Package: com.hkbigdata.mall.miaosha.config
 * Description:
 *
 * @Author BCXJ
 * @Create 2024/6/22 20:00
 * @Version 1.0
 * @Since 1.0
 */

import org.springframework.web.socket.*;

import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * WebSocket服务端
 */
public class WebSocketServer implements WebSocketHandler {

    private static final Set<WebSocketSession> sessions = new CopyOnWriteArraySet<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) {
        sessions.add(session);
        System.out.println("Connection opened: ");
    }

    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        String receivedText = (String) message.getPayload();
        for (int i = 0; i < 10; i++) {
            System.out.println("Received message: " + receivedText);
            Thread.sleep(1000);
        }
        System.out.println("Received message: " + receivedText);
        // Echo the message back to the client
        session.sendMessage(new TextMessage("Server received: " + receivedText));
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        sessions.remove(session);
        System.out.println("Connection closed due to error: " + session.getId());
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        sessions.remove(session);
        System.out.println("Connection closed: " + session.getId());
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }

}